package cn.gene.timeyan.ams.webapi.service.impl;

import cn.gene.timeyan.ams.service.IViolationService;
import cn.gene.timeyan.ams.webapi.mapper.ViolattionMapper;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.pojo.admin.dto.ViolationDTO;
import cn.gene.timeyan.pojo.admin.model.Violation;
import cn.gene.timeyan.pojo.admin.vo.ViolationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static cn.gene.timeyan.common.restful.ResponseCode.INTERNAL_SERVER_ERROR;

/**
 * 违规   服务实现类*
 *
 * @author LWG
 * @date 2022/7/21 17:48
 * @since 1.0.0@gene.cn
 */
@Slf4j
@Service
public class ViolationServiceImpl implements IViolationService {

    @Autowired
    private ViolattionMapper violattionMapper;

    @Override
    public void addViolation(ViolationDTO violationDTO) {
        log.trace("violationDTO", violationDTO);

        //查看是否已经封禁过了
        ViolationVO query = violattionMapper.selectViolationIdByUserId(violationDTO.getUserId());

        //如果为空，说明没封禁过，开始向封禁表添加数据
        if (query == null) {

            //创建对象
            Violation violation = new Violation();

            //补齐属性
            BeanUtils.copyProperties(violationDTO, violation);
            LocalDateTime now = LocalDateTime.now();
            violation.setCreateTime(now);
            violation.setUpdateTime(now);
            violation.setStartTime(now);
            violation.setEndTime(now.plusDays(violation.getBanDuration()));
            violation.setUserIp("昆明");

            //开始添加
            int rows = violattionMapper.addViolattion(violation);

            if (rows != 1) {
                throw new TimeyanServiceException(INTERNAL_SERVER_ERROR, "添加封禁信息失败，服务器忙，请稍后再次尝试！");
            }
        } else {
            //如果不为空，说明已封禁过，抛出异常
            log.error("该账号已封禁");
            throw new TimeyanServiceException(INTERNAL_SERVER_ERROR, "您已封禁过，请不要重复封禁！");
        }
    }
}
